package nuc.zhangchao.test.controller;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Zhang Chao
 * @Date 2020/12/30 7:15
 * @Version 1.0
 */
@Controller
public class FileController {


    @GetMapping("/file_upload")
    public String file_upload(){
        return "file_upload";
    }

    @PostMapping("/upload/multipart")
    public Map<String,Object> doUpload(@RequestParam("photo") MultipartFile photo){
//        String path = "F:/SpringbootSpace/finally_the_experimental/file";//保存路径
        String path ="src/main/resources/static";
        String filename = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        //获取上传文件的后缀suffix
        String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
            //Spring提供了文件操作类FileCopyUtils
            try {
                FileCopyUtils.copy(photo.getInputStream(),new FileOutputStream(path+filename+suffix));
            } catch (IOException e) {
                e.printStackTrace();
                return dealResultMap(false,"上传失败");
            }
            return dealResultMap(true,"上传成功");
    }
    private Map<String, Object> dealResultMap(boolean success, String msg) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", success);
        result.put("msg", msg);
        System.out.println(result);
        return result ;
    }
}
